import QueryMaterial2 from "@/components/QueryMaterial2";
import QueryMaterial3 from "@/components/QueryMaterial3";
import { s_caculateRequire, s_createProduceAlloc, s_getcommontableinfo, s_getSelectData, s_getSelectDataByCondition, s_getTableInfo, status2text } from "@/services/basis";
import { ActionType, EditableFormInstance, EditableProTable, ProCard, ProColumns, ProForm, ProFormDatePicker, ProFormDateRangePicker, ProFormDigit, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea, ProTable } from "@ant-design/pro-components";
import { Button, Col, Divider, List, message, Modal, Row, Space, Splitter, Tag,Image } from "antd";
import { withSuccess } from "antd/es/modal/confirm";
import moment from "moment";
import { useEffect, useRef, useState } from "react";

const App:React.FC=()=>{
    const [openRequire,setOpenRequire]=useState(false);
    const [openProduce,setOpenProduce]=useState(false);
    const [openFreeDispatch,setOpenFreeDispatch]=useState(false);
    const [openPurchase,setOpenPurchase]=useState(false);
    const [openCommission,setOpenCommission]=useState(false);
    const [openAdjustSuit,setOpenAdjustSuit]=useState(false);
    const [material,setMaterial]=useState([]);//查询物料组件结果


    const [materialOption,setMaterialOption]=useState([]);
    const [selectedPlanRecord,setSelectedPlanRecord]=useState<any[]>([]);

    const form_refMain=useRef<ProFormInstance>();
    const table_refMain=useRef<ActionType>();
    const etable_refMain=useRef<EditableFormInstance>();

    // 下达生产单界面
    const form_refProduce=useRef<ProFormInstance>();
    const editable_refProduce=useRef<EditableFormInstance>();
    const action_refProduce=useRef<ActionType>();
    const editable_refProduce2=useRef<EditableFormInstance>();//明细表
    const action_refProduce2=useRef<ActionType>();//明细表
    const [produceCard,setProduceCard]=useState<any[]>([]);
    const [selectedCard,setSelectedCard]=useState(0);//选中的工序卡片ID

    const form_refCaculate=useRef<ProFormInstance>();
    const [selectedPlan,setSelectedPlan]=useState<any[]>([]);

    //当组件选择物料时，更新表格并重载--------------
      useEffect(()=>{
                   if(material.length>0){
                   var x:any[]=editable_refProduce2.current?.getRowsData?.();
                   var quantity_total=form_refProduce.current?.getFieldValue('quantity_total');
           
                   // alert(JSON.stringify(x));
                   if(x==undefined)
                      x=[];
                      material.map((item:any)=>{
                      x?.push({rid:Math.random().toFixed(10),id:Math.random().toFixed(10).toString(),
                                material_id:item.id,code:item.code,name:item.name,
                                invstd:item.invstd,invstd2:item.invstd2,munit_name:item.munit_name,  
                                quantity_rate:'1/1', isbelongorder:1,
                                // userdefine_id:'[]',
                                pic:item.pic,
                                quantity_require:quantity_total?quantity_total:0,
                                quantity_stock:item.quantity_stock,
                                quantity_islock:item.quantity_islock,
                                quantity_enable:item.quantity_stock-item.quantity_islock,
                                quantity_diff:(quantity_total?quantity_total:0)
                                              -item.quantity_stock+item.quantity_stock,
                                    

                      });
                   });
     
                  //更新到useState中
                  var temp=produceCard.map((item:any)=>{
                      if(item.card_id==selectedCard)
                          return {...item,material_bom:x};
                      else
                         return item;
                  });
                   setProduceCard(temp);
                   form_refProduce.current?.setFieldValue('editable_produce2',x);
                   action_refProduce2.current?.reloadAndRest?.();
                }
                },[material]);
    

   interface DataType{
    rid?:number,id?:number,x_id?:number,org_id?:number,custom_id?:number,saletype_id?:number,
     order_code?:string,source_type?:string,did?:number,material_id?:number,userdefine_id?:string,userdefine_name?:string,
quantity?:number,deliverdate?:string,quantity_produce_order?:number,quantity_purchase_order?:number,
quantity_commission_order?:number,quantity_produce_done?:number,quantity_purchase_done?:number,
quantity_commission_done?:number,quantity_deliver?:number,quantity_stock?:number,
pic?:string,code?:string,name?:string,invstd?:string,munit_name?:string,stock_degree?:number,
craft_route_id?:number,craft_route_name?:string,status?:number,isproduce?:number,ispurchase?:number,
iscommission?:number,planning_type?:number,level?:number,begindate?:string,enddate?:string, 
   }

   const columns:ProColumns<DataType>[]=[
    {dataIndex:'rid',title:'rid',editable:false,},
      {dataIndex:'id',title:'id',editable:false,},
      {dataIndex:'org_name',title:'部门',editable:false,fixed:'left',width:100},
      {dataIndex:'business_name',title:'业务员',editable:false,fixed:'left',width:100},
      {dataIndex:'custom_name',title:'客户',editable:false,fixed:'left',width:100},
      {dataIndex:'order_code',title:'订单号',editable:false,fixed:'left',width:100},
      {dataIndex:'code',title:'商品编码',editable:false,},{dataIndex:'name',title:'名称',editable:false,},
      {dataIndex:'invstd',title:'规格',editable:false,},{dataIndex:'userdefine_name',title:'型号',editable:false,},
      {dataIndex:'munit_name',title:'单位',editable:false,},{dataIndex:'quantity',title:'订单数量',editable:false,},
      {dataIndex:'deliverdate',title:'交货日期',editable:false,valueType:'date'},
      {title:'已完成数',editable:false,
         render:(text,record,index)=><>{(record.quantity_produce_done?record.quantity_produce_done:0)
                                        +(record.quantity_purchase_done?record.quantity_purchase_done:0)
                                         +(record.quantity_commission_done?record.quantity_commission_done:0)}</>
      },
      {title:'累计下单数',editable:false,
        render:(text,record,index)=><>{(record.quantity_produce_order?record.quantity_produce_order:0)
                                        +(record.quantity_purchase_order?record.quantity_purchase_order:0)
                                         +(record.quantity_commission_order?record.quantity_commission_order:0)}</>
      },
      {dataIndex:'quantity_stock',title:'库存数',editable:false,},
      {dataIndex:'quantity_suit',title:'齐套数',editable:false,},
      
      // {dataIndex:'isproduce',title:'自产',valueType:'select',editable:false,
      //      valueEnum:{1:{text:'是'},0:{text:'-'}}
      // },
      // {dataIndex:'ispurchase',title:'外购',valueType:'select',editable:false,
      //      valueEnum:{1:{text:'是'},0:{text:'-'}}
      // },
      // {dataIndex:'iscommission',title:'委外',valueType:'select',editable:false,
      //      valueEnum:{1:{text:'是'},0:{text:'-'}},
            
      // },
      
      {dataIndex:'source_type',title:'来源',editable:false,
        valueType:'select',valueEnum:{1:{text:'销售订单'},2:{text:'采购订单'},3:{text:'委外订单'}}
      },
      {dataIndex:'planning_type',title:'计划类型',valueType:'select',
        valueEnum:{1:{text:'生产'},2:{text:'采购'},3:{text:'委外'}}
      },
      {dataIndex:'planning_quantity',title:'本次计划数',width:100},
      
      {dataIndex:'level',title:'级次',editable:false},
      {dataIndex:'stock_degree',title:'优先级',valueType:'select',width:80,
        valueEnum:{1:{text:'A'},2:{text:'B'},3:{text:'C'}}
      },
      {dataIndex:'begindate',title:'计划开始日期',valueType:'date'},
      {dataIndex:'enddate',title:'计划完成日期',valueType:'date'},
      {dataIndex:'craft_route_name',title:'工艺路线',editable:false,},
       
      {dataIndex:'status',title:'状态',editable:false,
        render:(text:any)=>status2text(text),
      },
      {
        dataIndex:'operate_time',title:'运算日期',editable:false,valueType:'dateTime'
      },
      // {
      //   valueType:'option',editable:false,
      //   render:()=><a>删除</a>
      // }
    ];

     
    interface DataType2{
      //  id,org_name,business_name,custom_name,code,name,invstd,userdefine_name,
      //  munit_name,quantity,deliverdate,quantity_doing,quantity_done,quantity2,quantity_plan,
      //  quantity_suit,priority,craft_route,bom_version,status,quantity_stock,
       pic?:string,
       rid?:number,id?:number,code?:string,name?:string,
       invstd?:string,userdefine_name?:string,munit_name?:string,quantity_rate?:string,quantity_islock?:number,
       quantity_require?:number,quantity_stock?:number,quantity_enable?:number,quantity_diff?:number, 
     }
  
     const columns2:ProColumns<DataType2>[]=[
      {dataIndex:'pic',title:'图片' ,editable:false,
        render:(text)=>{
            var pic=text=="-"||text==undefined?"":"/basis_api/file/get?filename="+text;
            return <Image src={pic}  
                   style={{width:50,height:50}} alt='无' />
       },
     },
         {dataIndex:'rid',title:'rid',editable:false,},
        {dataIndex:'id',hidden:true,editable:false,},
        {dataIndex:'code',title:'子件编码',editable:false,},{dataIndex:'name',title:'名称',editable:false,},
        {dataIndex:'invstd',title:'规格',editable:false,},{dataIndex:'userdefine',title:'型号',editable:false,},
        {dataIndex:'munit_name',title:'单位',editable:false,},
        {dataIndex:'quantity_rate',title:'换算率',width:100},
        {dataIndex:'quantity_require',title:'需求数',editable:false,},{dataIndex:'quantity_stock',title:'库存数',editable:false,},
        {dataIndex:'quantity_enable',title:'可用数',editable:false,},{dataIndex:'quantity_islock',title:'锁定数',editable:false,},
        {dataIndex:'quantity_diff',title:'欠料数',editable:false,
          render:(text:any)=>text>0?<Tag color="red" style={{width:50}}>{text}</Tag>:<Tag>{text}</Tag>,
        }, 
        {
          title:'操作',            
          fixed:'right',
          valueType:'option',
          width:80,
          editable:false,
          render:(text,record,_,action)=>[
            //  <a key='edit2'
            //     onClick={()=>{
            //         alert(record.rid);
            //        action?.startEditable?.(record.rid);}}
            //  >
            //      编辑
            //  </a>,
             <a  key='del2'
                 onClick={()=>{
                   var x:any[]=[];
                   x=editable_refProduce2.current?.getRowsData?.();
                   //  alert(JSON.stringify(x));
                   var temp=x.filter((item)=>item.rid!=record.rid);
                   var t=produceCard.map((item:any)=>{
                       if(item.card_id==selectedCard)
                             return {...item,material_bom:temp};
                         else
                             return item;
                    }) ;
                    //更新删除后的数据
                   setProduceCard(t); 
                   form_refProduce.current?.setFieldValue('editable_produce2',x.filter((item)=>item.rid!=record.rid));
                 }}
             >
                 删除
             </a>,
          ]
       }
      ];
   

      interface DataTypeBomDetail{
        id?:number,code?:string,name?:string,invstd?:string,munit_name?:string,
        quantity?:number,quantity_rate?:string,
        issuit?:string,quantity_diff?:number,
      };
      const columnsBomDetail:ProColumns<DataTypeBomDetail>[]=[
        {dataIndex:'id',title:'ID',hidden:true},{dataIndex:'code',title:'子件编码'},
        {dataIndex:'name',title:'名称'},{dataIndex:'invstd',title:'规格'},
        {dataIndex:'munit_name',title:'单位'},{dataIndex:'quantity',title:'需求总数量'},
        {dataIndex:'quantity_rate',title:'换算率'},{dataIndex:'issuit',title:'是否齐套'},
        {dataIndex:'quantity_diff',title:'缺料数量'},
      ];
      const tdataBomDetail:DataTypeBomDetail[]=[
        {code:'A22003366',name:'1#弯钩',invstd:'12*88-6',munit_name:'只',
            quantity:5000,quantity_rate:'1/10',issuit:'是',quantity_diff:0},
            {code:'B000001',name:'26#透明小象',invstd:'55#绿',munit_name:'只',
              quantity:500,quantity_rate:'1/1',issuit:'是',quantity_diff:200},
              {code:'C55566666',name:'透明内包装袋',invstd:'30*25',munit_name:'只',
                quantity:500,quantity_rate:'1/1',issuit:'是',quantity_diff:500},
      ]; 

      interface DataTypeBomDetailAdjust{
        id?:number,code?:string,name?:string,invstd?:string,munit_name?:string,
        warehouse?:string,quantity_stock?:number,isfixed?:string,isused?:string,source_order?:string,
      };
      const columnsBomDetailAdjust:ProColumns<DataTypeBomDetailAdjust>[]=[
        {dataIndex:'id',title:'ID',hidden:true},{dataIndex:'code',title:'子件编码'},
        {dataIndex:'name',title:'名称'},{dataIndex:'invstd',title:'规格'},
        {dataIndex:'munit_name',title:'计量单位'},{dataIndex:'quantity_stock',title:'库存数量'},
        {dataIndex:'warehouse',title:'仓库'},
        {dataIndex:'isfixed',title:'是否锁定'},{dataIndex:'isused',title:'是否占用'},
        {dataIndex:'source_order',title:'占用订单号'},
      ];

      const tdataBomDetailAdjust:DataTypeBomDetailAdjust[]=[
        {code:'B000001',name:'26#透明小象',invstd:'55#绿',munit_name:'只',
          quantity_stock:300,warehouse:'小仓',isfixed:'是',isused:'',source_order:''},
          {code:'B000001',name:'26#透明小象',invstd:'55#绿',munit_name:'只',
            quantity_stock:100,warehouse:'小仓',isfixed:'',isused:'是',source_order:'AM002566'},
            {code:'B000001',name:'30#透明小象',invstd:'56#浅绿',munit_name:'只',
              quantity_stock:200,warehouse:'大仓',isfixed:'是',isused:'',source_order:''},
      ];

      // 计算需求
      function caculateRequire(){
        setOpenRequire(true);
      }

      async function doCaculateRequire(){
           var fdata=form_refCaculate.current?.getFieldsValue();
           fdata={...fdata,
                 begindate:moment(moment(fdata.order_date[0]).toDate()).format('YYYY-MM-DD'),
                 enddate:moment(moment(fdata.order_date[1]).toDate()).format('YYYY-MM-DD'),
                 did:selectedPlan};
            // alert(JSON.stringify(fdata));
           const x=await s_caculateRequire({x_id:1,operater_id:1,fdata});
          //  alert(JSON.stringify(x.data[0]));
          //  alert(JSON.stringify(x.data[1]));
           if(x.success){
              message.success('计算需求成功！');
              // alert(JSON.stringify(x.data[0]));
              alert('注意保留已选择的行，不需要计算，仅更新需求数据；其他新行需重新生成计算')
              // form_refMain.current?.setFieldValue('editortable_main',x.data[0]);
              table_refMain.current?.reloadAndRest?.();
              }
            else
              message.error('计算失败，请联系管理员');
      }

      //调整计划
      function adjustPlan(){
        const x=form_refMain.current?.getFieldValue('editortable_main');
        // alert(JSON.stringify(x));
        x.map((item:any)=>{
          var rid=item.rid;
          table_refMain.current?.startEditable(rid);
        });
        
      }

      //调整保存计划
      function adjustPlanDone(){
        const x=form_refMain.current?.getFieldValue('editortable_main');
        // alert(JSON.stringify(x));
        x.map((item:any)=>{
          var rid=item.rid;
          table_refMain.current?.saveEditable(rid);
                      
        });
        
      }

      // 调整齐套
      function adjustSuit(){
        setOpenAdjustSuit(true);
      }

      // 根据选择的工序卡片，设置卡片信息和物料信息
      async function getCardDetail(card:any){
        //读取对应的子件明细，并赋给明细表
        // x_id,cate_id,id,source,fdata
        //当为空时，则调用产品工艺路线下BOM明细
        // alert(JSON.stringify(card));
        // alert(JSON.stringify(card.material_bom));
        var standard_bom:any[]=[];
        // alert(JSON.stringify(card));
        if(!card.material_bom){
        const x=await s_getcommontableinfo({x_id:1,cate_id:[],id:0,
                                             source:'v_material_craft_route_card_bom3',
                                             fdata:{
                                                material_id:selectedPlanRecord&&selectedPlanRecord.length>0?selectedPlanRecord[0].material_id:0,
                                                craft_route_id:selectedPlanRecord&&selectedPlanRecord.length>0?selectedPlanRecord[0].craft_route_id:0,
                                                card_id:card.card_id,
                                             }});
          standard_bom=x.data[0].map((item:any)=>{
        // 计算需求总数和差异
          var quantity_total=form_refProduce.current?.getFieldValue('quantity_total');
              quantity_total=quantity_total?quantity_total:0;
          var n1=item.quantity_rate.substring(0,item.quantity_rate.indexOf('/'));
          var n2=item.quantity_rate.substring(item.quantity_rate.indexOf('/')+1);
           return {...item,
               quantity_require:quantity_total*n2/n1,
               quantity_diff:quantity_total*n2/n1-item.quantity_stock+item.quantity_islock,
            };
          });
        //  alert(JSON.stringify(standard_bom));
        
       };//end if
        // alert(card.card_id);
        setSelectedCard(card.card_id);
        //更新produceCard----保存界面中的所有信息
        // var quantity_total=form_refProduce.current?.getFieldValue('quantity_total');
        // var quantity_unit=form_refProduce.current?.getFieldValue('quantity_unit');
        // var quantity_pc=form_refProduce.current?.getFieldValue('quantity_pc'); 
        var p=produceCard.map((item:any)=>{
            if(item.card_id==card.card_id)
              return {...item,
                material_bom:standard_bom.length==0?item.material_bom:standard_bom,
                quantity_total:card.quantity_total?card.quantity_total:0,
                quantity_unit:card.quantity_unit?card.quantity_unit:card.quantity_total?card.quantity_total:0,
                quantity_pc:card.quantity_pc?card.quantity_pc:1,  
               };
          else
             return {...item,
              // quantity_total:card.quantity_total?card.quantity_total:0,
              // quantity_unit:card.quantity_unit?card.quantity_unit:card.quantity_total?card.quantity_total:0,
              // quantity_pc:card.quantity_pc?card.quantity_pc:1, 
            };
         });
         setProduceCard(p);
        //  alert(JSON.stringify(p.filter(item=>item.card_id==card.card_id)));
         //更新界面表格
        form_refProduce.current?.setFieldsValue({
          card_id:card.card_id,
          default_workcenter_id:card.default_workcenter_id,
          default_workgroup_id:card.default_workgroup_id,
          
          begindate:card.begindate?card.begindate:moment(),
          enddate:card.enddate?card.enddate:moment(),
          quantity_total:card.quantity_total?card.quantity_total:0,
          quantity_unit:card.quantity_unit?card.quantity_unit:card.quantity_total?card.quantity_total:0,
          quantity_pc:card.quantity_pc?card.quantity_pc:1,
          editable_produce2:card.material_bom?card.material_bom:standard_bom, 
        });
      }

      //调整子件换算率
      function adjustQuantityRate(){
          const x=form_refProduce.current?.getFieldValue('editable_produce2');
          x.map((item:any)=>{
             action_refProduce2.current?.startEditable(item.rid);
          });
      }

      //保存子件换算率
      function saveQuantityRate(){
            const x=form_refProduce.current?.getFieldValue('editable_produce2');
            var t2=x.map((item:any)=>{
                action_refProduce2.current?.saveEditable(item.rid);
                var v=form_refProduce.current?.getFieldValue('quantity_total');
                var n1=item.quantity_rate.substring(0,item.quantity_rate.indexOf('/'));
                var n2=item.quantity_rate.substring(item.quantity_rate.indexOf('/')+1);
                n1=n1.length==0?1:n1;
                n2=n2.length==0?1:n2;
                item.quantity_require=(v?v:0)*n2/n1;
                item.quantity_diff=(v?v:0)*n2/n1-item.quantity_stock+item.quantity_islock;

                return item;
          });
          //更新卡片物料明细
          var t=produceCard.map((item:any)=>{
              if(item.card_id==selectedCard)
                  return {...item,material_bom:t2};
              else
                  return item;
          });
          setProduceCard(t);
      }

      //参数：1下达生产、2生产并派工--------------------------------------------------
      async function forProduce(etype:number){
         var t=produceCard.filter((item:any)=>!item.material_bom||item.material_bom.length==0); 
        if(form_refProduce.current?.getFieldValue('vouch_code')==undefined) // if 1
             message.warning('请填写生产单号');
        else if(t.length>0)
             message.warning('请先设置工序及物料明细');
        else{    
          const vouch_code=form_refProduce.current?.getFieldValue('vouch_code');
          const operate_time=form_refProduce.current?.getFieldValue('operate_time');
          const org_id=form_refProduce.current?.getFieldValue('org_id');
          const memo=form_refProduce.current?.getFieldValue('memo');
          const status=form_refProduce.current?.getFieldValue('status');
          // const begindate=form_refProduce.current?.getFieldValue('begindate');
          // const enddate=form_refProduce.current?.getFieldValue('enddate');
          // const craft_route_id=selectedPlanRecord[0].craft_route_id;
          // const source_mid=selectedPlanRecord[0].source_mid;
          // const source_did=selectedPlanRecord[0].source_did;
          // alert(JSON.stringify(produceCard));
          var card=produceCard.map((item:any)=>{
              return { 
                begindate:moment(moment(item.begindate).toDate()).format('YYYY-MM-DD'),
                enddate:moment(moment(item.enddate).toDate()).format('YYYY-MM-DD'),
                card_id:item.card_id,
                // card_name:item.card_name,
                workcenter_id:item.default_workcenter_id,
                workgroup_id:item.default_workgroup_id,
                quantity_total:item.quantity_total,
                quantity:item.quantity_unit,
                quantity_pc:item.quantity_pc,
                material_bom:item.material_bom.map((item2:any)=>({
                     material_id:item2.material_id,   
                     userdefine_id:item2.userdefine_id?JSON.parse(item2.userdefine_id):null,
                     userdefine_name:item2.userdefine_name,
                     quantity_rate:item2.quantity_rate,
                     quantity:item2.quantity_require,
                     })),
              };
          });
          
          var pitem=selectedPlanRecord[0];
          var plan={
               craft_route_id:pitem.craft_route_id,
               sourcetype_id:pitem.planning_type,
               source_mid:pitem.source_mid,
               source_did:pitem.source_did,
               material_id:pitem.material_id,
               userdefine_id:pitem.userdefine_id?JSON.parse(pitem.userdefine_id):null,
               userdefine_name:pitem.userdefine_name,
               quantity:pitem.planning_quantity,
               planning_begindate:moment(moment(pitem.planning_begindate).toDate()).format('YYYY-MM-DD'),
               planning_enddate:moment(moment(pitem.planning_enddate).toDate()).format('YYYY-MM-DD'),
               quantity_suit:pitem.quantity_suit,
               begindate:moment(moment(pitem.begindate).toDate()).format('YYYY-MM-DD'),
               enddate:moment(moment(pitem.enddate).toDate()).format('YYYY-MM-DD'),
              };

          // alert(JSON.stringify(plan));
          //  alert(JSON.stringify(card));
          // alert(JSON.stringify(produceCard));
        //   alert(JSON.stringify({x_id:1,operater_id:1,vtype:1,
        //     tdata:{vouch_code,org_id,memo,status,
        //           mdata:plan,
        //           fdata:card}
        //  }));
          const x=await s_createProduceAlloc({x_id:1,operater_id:1,vtype:etype,
             tdata:{vouch_code,org_id,memo,status,
                   mdata:plan,
                   fdata:card}
          });
          if(x.success){
                 message.success('下达成功！');
                 table_refMain.current?.reload?.();
                //  alert(JSON.stringify(produceCard));
                //  setProduceCard([]);
            }
          else
            message.error('下达失败，请检查');
        };// end if 1
      };

      //进入生产单主界面----------------------------------------------------------------
      function beginProduce(){
        if(selectedPlanRecord&&selectedPlanRecord.length!=1)
           message.warning('请选择、并仅选择一行需求。');
        else if(selectedPlanRecord[0].planning_type!=1)
          message.warning('请选择“计划类型：生产”的一行需求');
        else{
          //  setProduceCard([]);
           setOpenProduce(true);
        }
      };

      // 下达请购，则转入采购需求池--类型：采购
      async function beginPurchase(){
        if(selectedPlanRecord.length==0)
          message.warning('请先选择要操作的行');
        else
        alert("转入采购需求池："+JSON.stringify(selectedPlanRecord));
      };

      //下达委外，则转入采购需求池---类型：委外
      async function beginCommission(){
        if(selectedPlanRecord.length==0)
          message.warning('请先选择要操作的行');
        else
        alert("转入采购需求池--委外："+JSON.stringify(selectedPlanRecord));
      }

    //==========================================================================================================
    return <>
          <ProCard title='需求计划' style={{height:700,overflow:'auto'}} 
             extra={<Space>
                <Button onClick={()=>caculateRequire()}>计算需求</Button>
                <Button onClick={()=>adjustPlan()}>调整计划</Button>
                <Button onClick={()=>adjustPlanDone()}>保存计划</Button>
                {/* <Button onClick={()=>adjustSuit()}>调整齐套</Button> */}
                <Button onClick={()=>beginProduce()}>下达生产</Button>
                <Button onClick={()=>beginPurchase()}>下达采购申请</Button>
                <Button onClick={()=>beginCommission()}>下达委外申请</Button>
             </Space>}
          >
                <ProForm formRef={form_refMain} submitter={false}>
                <EditableProTable<DataType>
                    rowKey='rid'
                    name='editortable_main'
                    actionRef={table_refMain}
                    editableFormRef={etable_refMain}
                    search={false}
                    options={false}
                    columns={columns}
                    // dataSource={tdata}
                    // value={tdata}
                    rowSelection={{
                        type:'checkbox',
                        async onChange(selectedRowKeys:any, selectedRows:any, info) {
                          //  var did:any[]=[];
                          //  selectedRows.map((item:any)=>{
                          //      did.push({did:item.did,quantity_plan:item.quantity_plan,quantity_suit:item.quantity_suit});
                          //  });
                           setSelectedPlan(selectedRowKeys);
                           setSelectedPlanRecord(selectedRows);
                           //调取工序卡片，生成下单界面的工序列表
                          //  x_id,cate_id,id,source,fdata
                           const x=await s_getcommontableinfo({x_id:1,cate_id:[],
                                           id:selectedRows&&selectedRows.length>0?selectedRows[0].material_id:0,
                                           source:'v_material_craft_route_card',fdata:{}});
                            // alert(JSON.stringify(x.data[0]));
                           var a:any[]=[];
                           x.data[0].map((item:any)=>{
                             a.push({card_id:item.card_id,
                                     card_name:item.card_name,
                                     default_workcenter_id:item.default_workcenter_id,
                                     default_workgroup_id:item.default_workgroup_id,
                                     quantity_total:selectedRows&&selectedRows.length>0
                                           ?selectedRows[0].planning_quantity:0,
                                    //  material_bom:[],
                                    });
                           });

                           setProduceCard(a);
                        },
                    }}
                    editable={{
                      type:'multiple'
                    }}
                    recordCreatorProps={false}
                    request={async ()=>{
                      const x=await s_getTableInfo({x_id:1,source:'v_require_caculate',id:0})
                      return{
                        data:x.data,
                        success:true,
                      }
                    }}
                    columnEmptyText={false}
                    scroll={{y:500,x:'150%'}}
                    />
                 </ProForm>   
            </ProCard>  
            {/* 下达生产--------------------------------------------------------- */}
            <Modal title='下达生产' open={openProduce} width={'96%'} closable destroyOnClose 
                  onCancel={()=>setOpenProduce(false)}
                  onClose={()=>setOpenProduce(false)} okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}} 
                  style={{top:20}}
                >
                <ProCard style={{height:980}}
                   extra={<Space>
                        <Button  onClick={()=>forProduce(1)}>下达生产</Button>
                        <Button  onClick={()=>forProduce(2)}>下达生产并派工</Button>
                        
                   </Space>}
                >
                 <ProForm formRef={form_refProduce} submitter={false}
                     layout="horizontal" labelAlign="left" labelCol={{span:6,offset:0}}
                     initialValues={{
                         editable_produce:selectedPlanRecord.length>0?selectedPlanRecord:null,
                         quantity_total:selectedPlanRecord.length>0?selectedPlanRecord[0].planning_quantity:null,
                         operate_time:moment(),status:1,
                    }}
                 >
                  <Row gutter={8}>
                       <Col span={8}>
                           <ProFormText name='vouch_code' label='生产单号' width={200}
                             rules={[{required:true,message:'必填项'}]}
                           />
                           <ProFormSelect name='org_id' label='部门' width={200}
                                showSearch
                                       request={async ()=>{
                                           const x=await s_getSelectData({x_id:1,source:'base_organization'});
                                           return x.data;
                                         }}
                           />
                       </Col>
                       <Col span={8}>
                           <ProFormDatePicker name='operate_time' label='下单日期' width={200}/>
                           <ProFormRadio.Group name='status' label='状态' width={200} 
                           rules={[{required:true,message:'必填项'}]}
                               options={[{value:1,label:'正常'},{value:2,label:'冻结'},{value:3,label:'删除'}]}
                           />
                       </Col>
                       <Col span={8}>
                           <ProFormTextArea name='memo' label='备注' width={300}/>
                       </Col>
                    </Row>
                 <Splitter style={{ height: '100%', }} layout="vertical">
                      <Splitter.Panel defaultSize="40%" min="20%" max="70%" >
                        <ProCard  style={{height:360,overflow:'auto'}}>
                          {/* {JSON.stringify(produceCard)} */}
                        <EditableProTable<DataType>
                              name='editable_produce'
                              editableFormRef={editable_refProduce}
                              rowKey='rid'
                              search={false}
                              options={false}
                              columns={columns}
                               dataSource={[]}
                              // rowSelection={{
                              //     type:'checkbox',
                              // }}
                              recordCreatorProps={false}
                              actionRef={action_refProduce}
                              scroll={{y:260}}
                         />
                        </ProCard>
                      </Splitter.Panel>
                     <Splitter.Panel>
                        <Splitter style={{height:'100%'}}>
                            <Splitter.Panel defaultSize='10%'>
                              <List >
                                {/* <List.Item style={{width:100,marginLeft:50,fontWeight:'bold'}}>工艺流程</List.Item>
                                <List.Item style={{width:100,color:'red',marginLeft:50}}> 穿钩</List.Item>
                                <List.Item style={{width:100,color:'blue',marginLeft:50}}>贴牌</List.Item>
                                <List.Item style={{width:100,color:'blue',marginLeft:50}}>装袋</List.Item>
                                <List.Item style={{width:100,color:'blue',marginLeft:50}}>装箱</List.Item> */}
                                {
                                  produceCard.map((item:any)=><List.Item 
                                        style={{width:100,
                                                 marginLeft:60,
                                                color:selectedCard==item.card_id?'red':'blue'}}
                                                               onClick={()=>getCardDetail(item)}>
                                                              {item.card_name}</List.Item>)
                                }
                                </List>
                            </Splitter.Panel>
                            <Splitter.Panel defaultSize='30%'>
                            <List>
                                <List.Item style={{width:100,marginLeft:50,fontWeight:'bold'}}>工艺任务</List.Item>
                              </List>
                              {/* <ProForm submitter={false} layout="horizontal" labelAlign="left" labelCol={{offset:0,span:7}}
                                 style={{marginLeft:20}}  
                              > */}
                                  <Row gutter={8}>
                                    <Col span={12}> <ProFormSelect name='default_workcenter_id' label='生产中心' width={120} 
                                         showSearch
                                           request={async ()=>{
                                           const x=await s_getSelectData({x_id:1,source:'workcenter'});
                                               return x.data;
                                           }} 
                                           onChange={(value)=>{
                                                // alert(value);
                                                // alert(JSON.stringify(produceCard));
                                              var t=produceCard.map((item:any)=>{
                                                if(item.card_id==selectedCard)
                                                       item.default_workcenter_id=value;
                                                return item;
                                              });
                                              // alert(JSON.stringify(t));
                                              setProduceCard(t);
                                           }}
                                           /></Col>
                                    <Col span={12}> <ProFormSelect name='default_workgroup_id' label='生产组' width={120} 
                                         showSearch
                                         request={async ()=>{
                                         const x=await s_getSelectData({x_id:1,source:'workgroup'});
                                             return x.data;
                                         }} 
                                          onChange={(value)=>{
                                                // alert(value);
                                                // alert(JSON.stringify(produceCard));
                                              var t=produceCard.map((item:any)=>{
                                                if(item.card_id==selectedCard)
                                                       item.default_workgroup_id=value;
                                                return item;
                                              });
                                              // alert(JSON.stringify(t));
                                              setProduceCard(t);
                                           }}
                                        /></Col>
                                  </Row>
                                  <Row gutter={8}>
                                    <Col span={12}> <ProFormDatePicker name='begindate' label='开工日期' width={120}
                                        fieldProps={{
                                          onChange(date, dateString) {
                                           var t=produceCard.map((item:any)=>{
                                                if(item.card_id==selectedCard)
                                                       item.begindate=date;
                                                return item;
                                              });
                                              
                                              setProduceCard(t);
                                            
                                          },
                                        }}
                                    /></Col>
                                    <Col span={12}> <ProFormDatePicker name='enddate' label='完工日期' width={120}
                                        fieldProps={{
                                          onChange(date, dateString) {
                                           var t=produceCard.map((item:any)=>{
                                                if(item.card_id==selectedCard)
                                                       item.enddate=date;
                                                return item;
                                              });
                                              // alert(JSON.stringify(t));
                                              setProduceCard(t);
                                            
                                          },
                                        }}
                                    /></Col>
                                  </Row>
                                  <Divider/>
                                  <Row gutter={8}>
                                    <Col span={12}> 
                                        
                                        <ProFormDigit name='quantity_unit' label='派工单批量' width={100}
                                         
                                               fieldProps={{
                                               onChange:async (t2)=>{
                                                var t=produceCard.map((item:any)=>{
                                                if(item.card_id==selectedCard){
                                                       item.quantity_unit=t2;
                                                       var v=form_refProduce.current?.getFieldValue('quantity_total');
                                                        if(t2!=undefined&&t2!=0){
                                                          item.quantity_pc=Math.ceil((v?v:0)/t2);
                                                          
                                                          form_refProduce.current?.setFieldValue('quantity_pc',Math.ceil((v?v:0)/t2));
                                                          // alert(Math.ceil((v?v:0)/t2));
                                                       };
                                                   }
                                                return item;
                                              });
                                              //  alert(JSON.stringify(t));
                                              setProduceCard(t);
                                               }
                                            }}
                                            
                                        />
                                        <ProFormDigit name='quantity_total' label='派工总数' width={100}
                                            fieldProps={{
                                               onChange:async (v)=>{
                                                var t=produceCard.map((item:any)=>{
                                                if(item.card_id==selectedCard){
                                                       item.quantity_total=v;
                                                       var t2=form_refProduce.current?.getFieldValue('quantity_unit');
                                                        
                                                       if(t2!=undefined&&t2!=0){
                                                          item.quantity_pc=Math.ceil((v?v:0)/t2);
                                                          item.quantity_unit=t2;
                                                          form_refProduce.current?.setFieldValue('quantity_pc',Math.ceil((v?v:0)/t2));
                                                          // alert(Math.ceil((v?v:0)/t2));
                                                          //同步更新子件需求数量和差异
                                                        //  alert(JSON.stringify(item.material_bom));
                                                          var t3=item.material_bom.map((item2:any)=>{
                                                              var n1=item2.quantity_rate.substring(0,item2.quantity_rate.indexOf('/'));
                                                              var n2=item2.quantity_rate.substring(item2.quantity_rate.indexOf('/')+1);
                                                              item2.quantity_require=(v?v:0)*n2/n1;
                                                              item2.quantity_diff=(v?v:0)*n2/n1-item2.quantity_stock+item2.quantity_islock;
                                                              return item2; 
                                                            });
                                                           item.material_bom=t3;  
                                                           form_refProduce.current?.setFieldValue('editable_produce2',t3);
                                                          //  alert(JSON.stringify(t3));
                                                      };
                                                      return item; 
                                                   }else
                                                     return item;
                                                 
                                              });
                                              //  alert(JSON.stringify(t));
                                              setProduceCard(t);
                                               }
                                            }}
                                        />
                                    </Col>
                                    <Col span={12}>
                                         <ProFormText name='quantity_pc' label='派工单数'  width={100}
                                             
                                         />
                                         {/* <ProFormText name='print' label='打印派工单张数' width={100}
                                             placeholder={'0:所有，其他数字：批定张数'}
                                         /> */}
                                         {/* <Button>打印派工单</Button> */}
                                    </Col>
                                  </Row>
                                   
                              {/* </ProForm> */}
                            </Splitter.Panel>
                            <Splitter.Panel defaultSize='60%'>
                            <ProCard  style={{height:500,overflow:'auto'}}
                              extra={<Space>
                                <QueryMaterial3 setData={setMaterial} type='checkbox' x_id={1}/>
                                <Button onClick={()=>adjustQuantityRate()}>调整换算率</Button>
                                <Button onClick={()=>saveQuantityRate()}>保存换算率</Button>
                              </Space>}
                            >
                              
                              <EditableProTable<DataType2>
                                   name='editable_produce2'
                                   rowKey='rid'
                                   actionRef={action_refProduce2}
                                   editableFormRef={editable_refProduce2}
                                   search={false}
                                   options={false}
                                   columns={columns2}
                                  //dataSource={tdata2}
                                   rowSelection={{
                                        type:'checkbox',
                                     }}
                                    scroll={{y:350}}
                                   recordCreatorProps={false}
                                   editable={{
                                       type:'multiple'
                                   }}
                              />
                        </ProCard>
                            </Splitter.Panel>
                        </Splitter>
                     
                    </Splitter.Panel>
               </Splitter>
               </ProForm> 
               </ProCard>

            </Modal>
            {/* 需求计算------------------------------------------------------------- */}
            <Modal open={openRequire} okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}}
              closable onCancel={()=>setOpenRequire(false)} onClose={()=>setOpenRequire(false)} width='50%'
              destroyOnClose >
                 <ProCard title='需求计算设置' style={{height:600}}
                     extra={<Space>
                         <Button onClick={()=>form_refCaculate.current?.submit()}>开始计算</Button>
                         <Button onClick={()=>setOpenRequire(false)}>退出</Button>
                     </Space>}>
                        <ProForm submitter={false} layout="horizontal" labelAlign="left" labelCol={{offset:0,span:5}}
                            labelWrap formRef={form_refCaculate}
                            initialValues={{isrecaculate:0,isbydegree:1,order_date:[moment().add(-7,'day'),moment()]}}
                            onFinish={()=>doCaculateRequire()}
                          >
                            <ProFormDateRangePicker name='order_date' label='订单号日期' width={300} />
                            <ProFormText name='order_code' label='销售订单号' width={300}  />
                            <ProFormSelect name='custom_id' label='客户'  width={300} 
                                 showSearch
                                 request={async ()=>{
                                      const x=await s_getSelectData({x_id:1,source:'v_custom'});
                                      return x.data;
                                  }}
                            />
                            <ProFormSelect name='material_id' label='SKU名称'  width={300} 
                                showSearch
                                fieldProps={{
                                async  onSearch(value) {
                                    const x=await s_getSelectDataByCondition({x_id:1,source:'v_material',fdata:{value}});
                                    // return x.data;
                                  // alert(JSON.stringify(x.data));
                                  setMaterialOption(x.data);
                                  },

                                 async onChange(value, option) {
                                    // alert(value);
                                    // alert(JSON.stringify(option));
                                    // alert(JSON.stringify(option));
                                   
                                       },
                                  options:materialOption,
                                }}
                            />
                            <ProFormRadio.Group name='isrecaculate' label='已选择需求是否重新计算' width={300} 
                                options={[{value:0,label:'否'},{value:1,label:'是'}]}
                                
                               />
                            <ProFormRadio.Group name='isbydegree' label='是否按优先级顺序计算'  width={300} 
                               options={[{value:0,label:'否'},{value:1,label:'是'}]}
                               
                               />
                               
                        </ProForm>
                     </ProCard>
            
            </Modal>
            
             {/* 调整齐套------------------------------------------------------------- */}
             <Modal open={openAdjustSuit} okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}}
              closable onCancel={()=>setOpenAdjustSuit(false)} onClose={()=>setOpenAdjustSuit(false)} width='95%'
              destroyOnClose >
                 <ProCard title='调整齐套' style={{height:800}}
                     extra={<Space>
                         <Button>保存调整</Button>
                         <Button>退出</Button>
                     </Space>}>
                        <ProForm submitter={false} layout="horizontal" labelAlign="left" labelCol={{offset:0,span:5}}
                            labelWrap
                          >
                            <Row gutter={8}>
                              <Col span={8}>
                              <ProFormText name='f1' label='源销售订单号' width={200}/>
                              <ProFormText name='f2' label='客户' width={200}/>
                              <ProFormText name='f3' label='交货日期' width={200}/>
                              <ProFormText name='f4' label='备注' width={200}/>
                              </Col>
                              <Col span={8}>
                              <ProFormText name='f5' label='SKU编码' width={200}/>
                              <ProFormText name='f6' label='名称' width={200}/>
                              <ProFormText name='f7' label='规格' width={200}/>
                              <ProFormText name='f8' label='单位' width={200}/>
                              </Col>
                              <Col span={8}>
                              <ProFormText name='f9' label='订单总数量' width={200}/>
                              <ProFormText name='f10' label='累计完工数' width={200}/>
                              <ProFormText name='f11' label='未计划数' width={200}/>
                              <ProFormText name='f12' label='本次计划数' width={200}/>
                              </Col>
                            </Row>
                            <Row gutter={8}>
                              <Col span={10}>
                                 <ProCard title='订单子件需求表'>
                                    <ProTable<DataTypeBomDetail>
                                      search={false}
                                      options={false}
                                      columns={columnsBomDetail}
                                      dataSource={tdataBomDetail}
                                    />
                                 </ProCard>
                              </Col>
                              <Col span={14}>
                              <ProCard title='订单子件调整表'
                                 extra={<Space>
                                      <Button>添加替代料</Button>
                                      <Button>锁定</Button>
                                      <Button>取消锁定</Button>
                                      <Button>挪用</Button>
                                      <Button>取消挪用</Button>
                                 </Space>}
                              >
                                    <ProTable<DataTypeBomDetailAdjust>
                                      search={false}
                                      options={false}
                                      columns={columnsBomDetailAdjust}
                                      dataSource={tdataBomDetailAdjust}
                                    />
                                 </ProCard>
                              </Col>
                            </Row>
                        </ProForm>
                     </ProCard>
            
            </Modal>
    </>;
};

export default App;